﻿using System;
using System.Net;
using System.Text;
using System.Text.RegularExpressions;


namespace GoogleTranslateSidebarPlugin
{

    public static class Translator
    {

        /// <summary>
        /// Translates the text.
        /// </summary>
        /// <param name="input">The input.</param>
        /// <param name="languagePair">The language pair.</param>
        /// <returns></returns>
        public static string TranslateText(string input, string languagePair)
        {
            return TranslateText(input, languagePair, System.Text.Encoding.UTF8);
        }

        /// <summary>
        /// Translate Text using Google Translate
        /// </summary>
        /// <param name="input">The string you want translated</param>
        /// <param name="languagePair">2 letter Language Pair, delimited by "|". 
        /// e.g. "en|da" language pair means to translate from English to Danish</param>
        /// <param name="encoding">The encoding.</param>
        /// <returns>Translated to String</returns>
        public static string TranslateText(string input, string languagePair, Encoding encoding)
        {
            string url = String.Format("http://ajax.googleapis.com/ajax/services/language/translate?v=1.0&q={0}&langpair={1}&key={2}", System.Web.HttpUtility.UrlEncode(input), languagePair, "ABQIAAAAIuckriZuRA3FYdnyrDw-AhSjNWOZoB0auXpsmkMg8ggGncMXqhS0My6GzcyAUgk6vV4pWciUdN4aPA");

            
            string result = String.Empty;

            using (WebClient webClient = new WebClient())
            {
                webClient.Encoding = encoding;
                result = webClient.DownloadString(url);
            }
           
            Match m = Regex.Match(result, "(?<=<div id=result_box dir=\"ltr\">)(.*?)(?=</div>)");
            result = result.Substring(36, result.Length - 36 - 51);
            if (m.Success)
                result = m.Value;

            return result;
        }
    }

}
